package com.glory.brepda.activity.mfg;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.glory.brepda.R;
import com.glory.brepda.adapter.AddCarrierDataAdapter;
import com.glory.brepda.adapter.DefectListAdapter;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.base.MyApp;
import com.glory.brepda.callback.CustomDialogEntityCallBack;
import com.glory.brepda.entity.DefectCodeEntity;
import com.glory.brepda.entity.LotInfoEntity;
import com.glory.brepda.entity.LotLists;
import com.glory.brepda.entity.LotactionLists;
import com.glory.brepda.entity.ScrapEntity;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.LotUtils;
import com.glory.brepda.utils.NetUtils;
import com.glory.brepda.utils.ShowDialog;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_LogUtils;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_ToastUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * FileName: newCommonlyEndActivity
 * Author: xuyifan902315
 * Date: 2025/2/21 11:43
 * Description:新一般出站
 * History:
 */
public class newCommonlyEndActivity extends BaseActivity implements TextWatcher {

    @BindView(R.id.etTitle)
    FreeUI_ClearEditText etTitle;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvSub)
    TextView tvSub;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.tvLotState)
    TextView tvLotState;
    @BindView(R.id.etLot)
    FreeUI_ClearEditText etLot;
    @BindView(R.id.tvEqpWorkID)
    TextView tvEqpWorkID;
    @BindView(R.id.tvStep)
    TextView tvStep;
    @BindView(R.id.etTrackOutNum)
    TextView etTrackOutNum;
    @BindView(R.id.etProjectNum)
    FreeUI_ClearEditText etProjectNum;
    @BindView(R.id.etComment)
    FreeUI_ClearEditText etComment;
    @BindView(R.id.etMaterielModel)
    FreeUI_ClearEditText etMaterielModel;
    @BindView(R.id.rvMaterielModelList)
    RecyclerView rvMaterielModelList;
    @BindView(R.id.etMaterielBox)
    FreeUI_ClearEditText etMaterielBox;
    @BindView(R.id.rvMaterielBoxList)
    RecyclerView rvMaterielBoxList;
//    @BindView(R.id.ivDefectArrow)
//    ImageView ivDefectArrow;
//    @BindView(R.id.flDefectList)
//    FrameLayout flDefectList;
    @BindView(R.id.rvScrapList)
    RecyclerView rvScrapList;
    @BindView(R.id.tvScrapNum)
    TextView tvScrapNum;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    @BindView(R.id.llEap)
    LinearLayout llEap;
    @BindView(R.id.rlEap)
    RelativeLayout rlEap;
    @BindView(R.id.rvEdcDataList)
    RecyclerView rvEdcDataList;
    @BindView(R.id.etThinning)
    FreeUI_ClearEditText etThinning;
    @BindView(R.id.etTotalNumber)
    FreeUI_ClearEditText etTotalNumber;
    @BindView(R.id.tvPauseStatus)
    TextView tvPauseStatus;
    @BindView(R.id.lotScan)
    ImageView lotScan;
    @BindView(R.id.modelScan)
    ImageView modelScan;
    @BindView(R.id.boxScan)
    ImageView boxScan;
    @BindView(R.id.tvtMatCount)
    TextView tvtMatCount;

    // 载具：黑箱输入框
    @BindView(R.id.etBlackCase)
    FreeUI_ClearEditText etBlackCase;

    private static final int REQUEST_CODE_TEXT1 = 1001;
    private static final int REQUEST_CODE_TEXT2 = 1002;
    private static final int REQUEST_CODE_TEXT3 = 1003;
    private List<String> defectCodeList;
    private FreeUI_GeneralPop codePop;
    private DefectListAdapter defectListAdapter;
    private LotInfoEntity lotInfoEntity;
    private AddCarrierDataAdapter materielModelAdapter;
    private AddCarrierDataAdapter materielBoxAdapter;
    private List<String> mDurablelist;
    private String defectCode = "";
    private long subqty = 0;
    private boolean isetTrackOutNum = true;
    private String title;
    private String orderScrapNum = "0";
    private String orderMainQty = "0";
    private String lotTotalScrap = "0";

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_commonly_new;
    }

    @Override
    protected void initView() {

        title = getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY);
        tvSub.setText("数量");
        tvBaseSubmit.setText("下一步");
        tvTitle.setText(title);
        setMainLayout(llMain);
        rvEdcDataList.setVisibility(View.GONE);
        llEap.setVisibility(View.GONE);
        rlEap.setVisibility(View.GONE);
        etLot.requestFocus();
        defectCodeList = new ArrayList<>();
        initRecyclerView(rvScrapList, this);
        defectListAdapter = new DefectListAdapter(null, tvScrapNum, false);
        defectListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        defectListAdapter.isFirstOnly(true);
        rvScrapList.setAdapter(defectListAdapter);

        initRecyclerView(rvMaterielModelList, this);
        initRecyclerView(rvMaterielBoxList, this);
        materielModelAdapter = getCarrierAdapter();
        rvMaterielModelList.setAdapter(materielModelAdapter);
        materielBoxAdapter = getCarrierAdapter();
        rvMaterielBoxList.setAdapter(materielBoxAdapter);
        etLot.addTextChangedListener(this);
        etTrackOutNum.addTextChangedListener(this);
        etProjectNum.addTextChangedListener(this);

        defectListAdapter.setListener(new DefectListAdapter.onListener() {
            @Override
            public void OnListener(String s, ScrapEntity item) {
                try {
                    item.setMAINQTY(s.toString());

                    item.setMAINQTY(s.toString());
                    item.setSUBQTY(s.toString());
                    ScrapEntity.MainQTY mainQTY = new ScrapEntity.MainQTY(s.toString());
                    List<ScrapEntity.MainQTY> data = new ArrayList<>();
                    data.add(mainQTY);
                    item.setQTYLIST(data);
                    long num = defectListAdapter.Calculation();
                    if (num < 0) {
                        FreeApi_ToastUtils.showFreeToast("不良数量大于批次数量，请重新输入", MyApp.app, false, Toast.LENGTH_LONG);
                        item.setMAINQTY("0");
                        item.setSUBQTY("0");
                        ScrapEntity.MainQTY mainQTY1 = new ScrapEntity.MainQTY("0");
                        List<ScrapEntity.MainQTY> data1 = new ArrayList<>();
                        data.add(mainQTY1);
                        item.setQTYLIST(data1);
                        tvScrapNum.setText("0");
                    } else {
                        tvScrapNum.setText(num + "");
                    }

                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
        });

        etTrackOutNum.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (b && isetTrackOutNum) {
                    isetTrackOutNum = false;
                    etLot.requestFocus();
                }
            }
        });

        initEdit(etLot, s -> {
            if (s.equals("Submit")) {
                Submit();
                etLot.setText("");
                etLot.requestFocus();
                return;
            }
            //获取lot信息
            LotUtils.searchLotInfo(newCommonlyEndActivity.this, s, getSupportFragmentManager(), new LotUtils.netCallback<LotInfoEntity>() {
                @Override
                public void onSuccess(LotInfoEntity response) {
                    getOrderScrapData();
                    lotInfoEntity = response;
                    if(StringUtils.isNotEmpty(response.getTip())){
                        ShowDialog.showDialog(newCommonlyEndActivity.this,response.getTip(),"制程风险提示");
                    }
                    subqty = Integer.parseInt(response.getLOT().getMAINQTY());
                    tvEqpWorkID.setText(response.getLOT().getEQUIPMENTID());
                    tvStep.setText(response.getLOT().getSTEPNAME() + "/" + response.getLOT().getSTEPDESC());
                    etProjectNum.setText(String.valueOf(response.getPACKAGETYPEQTY()));
                    mDurablelist = response.getDURABLELIST();
                    etTrackOutNum.setText(response.getLOT().getMAINQTY());
                    materielModelAdapter.setNewData(mDurablelist);
                    tvLotState.setText(response.getLOT().getSTATE());
                    tvPauseStatus.setText(response.getLOT().getHOLDSTATE());
                    defectListAdapter.setTotalNum(Integer.parseInt(response.getLOT().getMAINQTY()));
                    tvtMatCount.setText(response.getLOT().getUDF().getaMatCount());
                    getDefectInfo();
                }

                @Override
                public void onFail(Throwable t) {
                    loadError(t, "LOTQUERY");
                }
            });
        });


        initEdit(etMaterielModel, s -> {
//            if (mDurablelist == null){
//                showToast("请先扫描批次号!", false);
//                return;
//            }
            if (s.equals("Submit")) {
                Submit();
                etMaterielModel.setText("");
                etMaterielModel.requestFocus();
                return;
            }
            if (materielModelAdapter.getData().contains(s)) {
                showToast("当前载具已添加到载具列表中", false);
                return;
            }

            materielModelAdapter.getData().add(s);
            materielModelAdapter.notifyDataSetChanged();
        });

        initEdit(etMaterielBox, s -> {
            if (s.equals("Submit")) {
                Submit();
                etMaterielBox.setText("");
                etMaterielBox.requestFocus();
                return;
            }

            if (mDurablelist == null) {
                showToast("请先扫描批次号!", false);
                return;
            }

            if (materielBoxAdapter.getData().contains(s)) {
                showToast("当前料盒已添加到列表中", false);
                return;
            }

            materielBoxAdapter.getData().add(s);
            materielBoxAdapter.notifyDataSetChanged();
            etMaterielBox.setText("");
            etMaterielBox.requestFocus();
        });

        etTrackOutNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
//                defectListAdapter.setTotalNum(editable.toString().equals("")? 0 : Integer.parseInt(editable.toString()));
                if (subqty > 0) {
                    if (!editable.toString().equals("")) {
                        if (Long.parseLong(editable.toString()) > subqty) {
                            showToast("出站Die数量不能大于进站数量", false);
                            etTrackOutNum.setText(subqty + "");
                        } else {
                            defectListAdapter.setTotalNum(editable.toString().equals("") ? 0 : Long.parseLong(editable.toString()));
                        }
                    }
                } else {
                    showToast("进站数量为空", false);
                }
            }
        });

        initEdit(etTitle, s -> {

            if (!s.equals("Submit")) {
                return;
            }
            LotUtils.lotDAWBTrackOut(this, "GENERALLOTTRACKOUT", getSupportFragmentManager(), "", tvEqpWorkID.getText().toString(),
                    getText(etLot), defectListAdapter.getData(), materielModelAdapter.getData(), defectCode, etTrackOutNum.getText().toString(), lotInfoEntity,
                    tvScrapNum.getText().toString().equals("") ? 0 : Integer.parseInt(tvScrapNum.getText().toString()),
                    etTrackOutNum.getText().toString(),null, new LotUtils.netCallback() {
                
                        @Override
                        public void onSuccess(Object response) {

                        }

                        @Override
                        public void onFail(Throwable t) {
                            if (!tvScrapNum.getText().toString().equals("")) {
                                int defectNum = Integer.parseInt(tvScrapNum.getText().toString());
                                etTrackOutNum.setText(String.valueOf(Integer.parseInt(etTrackOutNum.getText().toString()) + defectNum));
                            }
                        }
                    });
        });

    }

    private void getOrderScrapData() {
        FreeUI_EntityCallBack<BaseResponseBean<JsonObject>> callback = new FreeUI_DialogEntityCallBack<BaseResponseBean<JsonObject>>
                (new TypeToken<BaseResponseBean<JsonObject>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<JsonObject>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    JsonObject jsonObject = response.body().getResponse().getBody();
                    orderScrapNum=jsonObject.get("ORDER_SCRAP_NUM").getAsString();
                    orderMainQty=jsonObject.get("ORDER_MAIN_QTY").getAsString();
                    lotTotalScrap=jsonObject.get("LOT_SCRAP_NUM").getAsString();
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<JsonObject>> response) {
                super.onError(response);
                loadError(response.getException(), "GETORDERSCRAPDATA");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE", "SCRAPDATA");
        map.addProperty("LOT_ID", getText(etLot));
        NetUtils.requestPostNet("IF.GETORDERSCRAPDATA", "Common", newCommonlyEndActivity.this, map, callback);
    }

    private void getDefectInfo() {

        FreeUI_EntityCallBack<BaseResponseBean<DefectCodeEntity>> callback = new FreeUI_DialogEntityCallBack<BaseResponseBean<DefectCodeEntity>>
                (new TypeToken<BaseResponseBean<DefectCodeEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<DefectCodeEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(), true, getSupportFragmentManager())) {
                    defectCodeList.clear();
                    List<DefectCodeEntity.DefectCode> scrapcodelists = response.body().getResponse().getBody().getADREFLIST();
                    for (DefectCodeEntity.DefectCode code : scrapcodelists) {
                        defectCodeList.add(code.getKEY() + "/" + code.getDESCRIPTION());
                        ScrapEntity scrapEntity = new ScrapEntity();
                        scrapEntity.setACTIONCODE(code.getKEY());
                        scrapEntity.setACTIONREASON(code.getDESCRIPTION());
                        scrapEntity.setLOTID(lotInfoEntity.getLOT().getLOTID());
                        scrapEntity.setLOTRRN(lotInfoEntity.getLOT().getOBJECTRRN());
                        scrapEntity.setACTIONTYPE("Scrap");
                        scrapEntity.setSUBQTY("");
//                        scrapEntity.setSUBQTY(subqty+"");
//                        if (defectListAdapter.getData().size() > 0) {
//                            if (containCode(scrapEntity)) {
//                                defectListAdapter.addData(scrapEntity);
//                            }
//                        } else {
//                            defectListAdapter.addData(scrapEntity);
//                        }
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<DefectCodeEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "GETSTEPBYLOT");
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("REFERENCENAME", lotInfoEntity.getSTEPLIST().get(0).getSCRAPCODESRC());
        map.addProperty("REFERENCETYPE", "USER");
        NetUtils.requestPostNet("IF.ADREFLISTQUERY", "Common", newCommonlyEndActivity.this, map, callback);
    }

    @Override
    protected void initData() {

        lotScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startQrScanner(REQUEST_CODE_TEXT1);
            }
        });
        modelScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startQrScanner(REQUEST_CODE_TEXT2);
            }
        });
        boxScan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startQrScanner(REQUEST_CODE_TEXT3);
            }
        });

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK && data != null) {
            String qrResult = data.getStringExtra("SCAN_RESULT"); // 获取扫码结果
            if (qrResult != null) {
                switch (requestCode) {
                    case REQUEST_CODE_TEXT1:
                        etLot.setText(qrResult);
                        break;
                    case REQUEST_CODE_TEXT2:
                        etMaterielModel.setText(qrResult);
                        break;
                    case REQUEST_CODE_TEXT3:
                        etMaterielBox.setText(qrResult);
                        break;
                }
            }

        }
        if (requestCode == 1){
            finish();
        }
    }



    private void Submit() {
        if (getText(etLot).equals("")) {
            showToast("请先扫描批次信息", false);
            etLot.requestFocus();
            return;
        }

        if (tvLotState.getText().toString().equals("待投产")) {
            showConfirmDialog("批次未投产，请联系计划部执行投产");
            return;
        }

        if (tvLotState.getText().toString().equals("等待作业")) {
            showConfirmDialog("批次没有作业，请操作进站功能");
            return;
        }

        if (etTrackOutNum.getText().toString().toString().equals("")) {
            showToast("出站Die数量不能为空", false);
            return;
        }

        List<String> data = materielModelAdapter.getData();

        String defectNum = tvScrapNum.getText().toString().equals("") ? "0" : tvScrapNum.getText().toString();
        String trackOutNum = etTrackOutNum.getText().toString().equals("") ? "0" : etTrackOutNum.getText().toString().toString();
        int defect = Integer.parseInt(defectNum) + Integer.parseInt(trackOutNum);

        if (defect != subqty) {
            showToast("报废数量输入不正确", false);
            return;
        }

        if (Long.parseLong(tvScrapNum.getText().toString().equals("") ? "0" : tvScrapNum.getText().toString()) > subqty) {
            showToast("不良数大于进站数", false);
            return;
        }

        List<String> dataBox = materielBoxAdapter.getData();
        data.addAll(dataBox);
//                LotUtils.lotTrackOut(this, getSupportFragmentManager(), equipmentid, getText(etLot), defectListAdapter.getData(),data);

        FreeUI_EntityCallBack<BaseResponseBean<LotInfoEntity>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<LotInfoEntity>>
                (new TypeToken<BaseResponseBean<LotInfoEntity>>() {
                }.getType(), getSupportFragmentManager(), newCommonlyEndActivity.this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<LotInfoEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(newCommonlyEndActivity.this, false, getSupportFragmentManager())) {
                    FreeApi_ToastUtils.showFreeToast("出站成功", newCommonlyEndActivity.this, true, 0);
                    finish();
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<LotInfoEntity>> response) {
                super.onError(response);
                FreeApi_LogUtils.saveErrorMessages(response.getException(), "LOTTRACKOUT");
                FreeApi_ToastUtils.showFreeToast("连接服务器失败", newCommonlyEndActivity.this, false, 0);
            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE", "DefaultTrackOut");
        map.addProperty("EQUIPMENTID", tvEqpWorkID.getText().toString());
        map.addProperty("CARRIERACTION", "");
        map.addProperty("DURABLE", "");
        map.addProperty("ALLREWORKFLAG", "N");
        map.addProperty("WAREHOUSEID", defectCode);
        map.addProperty("STORAGEID", "");
        map.addProperty("THINNING",getText(etThinning));
        map.addProperty("TOTALNUMBER", getText(etTotalNumber));
        List<LotLists> lotList = new ArrayList<>();
        List<LotactionLists> lotactionList = new ArrayList<>();
        LotLists lotList1 = new LotLists(getText(etLot));
        lotList.add(lotList1);

        if (defectListAdapter.getData() != null) {
            for (ScrapEntity mDefectData : defectListAdapter.getData()) {
                ArrayList<LotactionLists.QTYList> qtyList = new ArrayList<>();
                LotactionLists.QTYList qtybean = new LotactionLists.QTYList();

                qtybean.setSUBQTY(mDefectData.getMAINQTY());
                qtybean.setMAINQTY("0");
                qtyList.add(qtybean);

//                    LotactionLists lotactionLists = new LotactionLists(lotID,
//                            mDefectData.getACTIONCODE(),
//                            mDefectData.getACTIONREASON(),
//                            method.equals("Common") ? mDefectData.getMAINQTY() : "0",
//                            method.equals("Common") ? "0" : mDefectData.getMAINQTY(),
//                            qtyList);

                LotactionLists lotactionLists1 = new LotactionLists();
                lotactionLists1.setLOTID(getText(etLot));
                lotactionLists1.setACTIONCODE(mDefectData.getACTIONCODE());
                lotactionLists1.setACTIONREASON(mDefectData.getACTIONREASON());
                lotactionLists1.setACTIONTYPE("Scrap");
                lotactionLists1.setSUBQTY(mDefectData.getMAINQTY());
                lotactionLists1.setMAINQTY("0");
                lotactionLists1.setQTYLIST(qtyList);

                lotactionList.add(lotactionLists1);

            }
        }

        map.add("LOTLIST", new JsonParser().parse(new Gson().toJson(lotList)).getAsJsonArray());//传批次集合
        map.add("LOTACTIONLIST", new JsonParser().parse(new Gson().toJson(lotactionList)).getAsJsonArray());
        map.add("DURABLEIDLIST", new JsonParser().parse(new Gson().toJson(materielBoxAdapter.getData())).getAsJsonArray());
        NetUtils.requestPostNet("IF.LOTTRACKOUT", "GENERALLOTTRACKOUT", newCommonlyEndActivity.this, map, callBack);

    }

    @OnClick({R.id.tvBaseSubmit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tvBaseSubmit:
//                if (actionControl("Submit24")) {
//                    return;
//                }
                if (getText(etLot).equals("") || lotInfoEntity == null) {
                    showToast("请先扫描批次信息", false);
                    etLot.requestFocus();
                    return;
                }

                if (tvLotState.getText().toString().equals("待投产")) {
                    showConfirmDialog("批次未投产，请联系计划部执行投产");
                    return;
                }

                if (tvLotState.getText().toString().equals("等待作业")) {
                    showConfirmDialog("批次没有作业，请操作进站功能");
                    return;
                }

                if (etTrackOutNum.getText().toString().toString().equals("")) {
                    showToast("出站Die数量不能为空", false);
                    return;
                }

                if (lotInfoEntity.getLOT().getSTEPNAME().equals("T0500")){
                    showToast("必须要用MES操作",false);
                    return;
                }



                int sumDefect = 0;
                if (defectListAdapter.getData() != null) {
                    for (ScrapEntity entity : defectListAdapter.getData()) {
                        sumDefect += Integer.parseInt(entity.getMAINQTY().equals("") ? "0" : entity.getMAINQTY());
                    }
                } else {
                    sumDefect += 0;
                }
                tvScrapNum.setText(sumDefect + "");
                List<String> data = materielModelAdapter.getData();
                String defectNum = tvScrapNum.getText().toString().equals("") ? "0" : tvScrapNum.getText().toString();
                String trackOutNum = etTrackOutNum.getText().toString().equals("") ? "0" : etTrackOutNum.getText().toString();
                int defect = Integer.parseInt(defectNum) + Integer.parseInt(trackOutNum);

                if (defect != subqty) {
                    showToast("报废数量输入不正确", false);
                    return;
                }

                if (Long.parseLong(tvScrapNum.getText().toString().equals("") ? "0" : tvScrapNum.getText().toString()) > subqty) {
                    showToast("不良数大于进站数", false);
                    return;
                }
//                Integer aMatCount = Integer.parseInt(tvtMatCount.getText().toString());
                List<String> dataBox = materielBoxAdapter.getData();
                data.addAll(dataBox);
                // 设置黑箱（载具）信息
                lotInfoEntity.setCARRIERCASE(getText(etBlackCase));

                Bundle bundle = new Bundle();
                bundle.putString("LOTID",getText(etLot));
                bundle.putString("EQPID",tvEqpWorkID.getText().toString());
                bundle.putString("DEFECTCODE",defectNum);
                bundle.putString("SCRAPCODESRC",tvScrapNum.getText().toString().equals("")?"0":tvScrapNum.getText().toString());
                bundle.putString("TRACKOUTNUM",etTrackOutNum.getText().toString());
                bundle.putString("method","GENERALLOTTRACKOUT");
                bundle.putSerializable("LOTINFOENTITY", lotInfoEntity);
                bundle.putSerializable("ScrapList", (Serializable)defectListAdapter.getData());
                bundle.putString("title", title);
                bundle.putString("THINNING",getText(etThinning));
                bundle.putString("TOTALNUMBER", getText(etTotalNumber));
                bundle.putString("orderScrapNum",orderScrapNum);
                bundle.putString("orderMainQty",orderMainQty);
                bundle.putString("lotTotalScrap",lotTotalScrap);
                bundle.putString("aMatCount", tvtMatCount.getText().toString());//实际排数
                bundle.putStringArrayList("MATERIELMODELLIST", (ArrayList<String>) data);
                Intent intent = new Intent(this, WorkEnd3Activity.class);
                intent.putExtras(bundle);
                startActivityForResult(intent,1);

//                LotUtils.lotDAWBTrackOut(this, "GENERALLOTTRACKOUT", getSupportFragmentManager(), "", tvEqpWorkID.getText().toString(),
//                        getText(etLot), defectListAdapter.getData(), data, defectCode, String.valueOf(subqty), lotInfoEntity,
//                        tvScrapNum.getText().toString().equals("") ? 0 : Integer.parseInt(tvScrapNum.getText().toString()),
//                        etTrackOutNum.getText().toString(), null,new LotUtils.netCallback() {
//                            @Override
//                            public void onSuccess(Object response) {
//
//                            }
//
//                            @Override
//                            public void onFail(Throwable t) {
//                                if (!tvScrapNum.getText().toString().equals("")) {
//                                    int defectNum = Integer.parseInt(tvScrapNum.getText().toString());
//                                    etTrackOutNum.setText(String.valueOf(Integer.parseInt(etTrackOutNum.getText().toString()) + defectNum));
//                                }
//                            }
//                        });
                break;
//            case R.id.flDefectList:
//                if (defectCodeList.size() <= 0) {
//                    showToast("未获取到不良代码列表", false);
//                    return;
//                }
//
//                if (codePop != null) {
//                    if (codePop.isShowing()) {
//                        codePop.dismiss();
//                    }
//                } else {
//                    codePop = FreeApi_PopUtils.getNormalPop(getApplicationContext(), flDefectList.getWidth(), defectCodeList, ivDefectArrow, (codeS, i) -> {
//                        tvDefectCode.setText(codeS.split("/")[0]);
//                        ScrapEntity scrapEntity = new ScrapEntity();
//                        scrapEntity.setACTIONCODE(codeS.split("/")[0]);
//                        scrapEntity.setACTIONREASON(codeS.split("/")[1]);
//                        scrapEntity.setLOTID(lotInfoEntity.getLOT().getLOTID());
//                        scrapEntity.setLOTRRN(lotInfoEntity.getLOT().getOBJECTRRN());
//                        scrapEntity.setACTIONTYPE("Scrap");
//                        scrapEntity.setSUBQTY(subqty + "");
//                        defectCode = codeS.split("/")[0];
//                        if (defectListAdapter.getData().size() > 0) {
//                            if (containCode(scrapEntity)) {
//                                defectListAdapter.addData(scrapEntity);
//                            }
//                        } else {
//                            defectListAdapter.addData(scrapEntity);
//                        }
//
//                    });
//                }
//                FreeApi_PopUtils.setArrowShow(ivDefectArrow);
//                codePop.showAsDropDown(flDefectList, 0, 0);
//                break;
        }
    }

//    private boolean containCode(ScrapEntity scrapEntity) {
//        for (ScrapEntity bean : defectListAdapter.getData()) {
//            if (bean.getACTIONCODE().equals(scrapEntity.getACTIONCODE())) {
//                showToast("列表中已有当前不良代码!", false);
//                return false;
//            }
//        }
//        return true;
//    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                break;
            case MotionEvent.ACTION_UP:
                if (defectListAdapter.getData().size() != 0) {
                    String defectNum = tvScrapNum.getText().toString().equals("") ? "0" : tvScrapNum.getText().toString();
                    String trackOutNum = etTrackOutNum.getText().toString().equals("") ? "0" : etTrackOutNum.getText().toString();

                    int defect = Integer.parseInt(defectNum) + Integer.parseInt(trackOutNum);

                    if (defect == subqty && Long.parseLong(tvScrapNum.getText().toString().equals("") ? "0" : tvScrapNum.getText().toString()) <= subqty) {
                        etTitle.setText("");
                        etTitle.requestFocus();
                    }
                }

                break;
        }
        return super.dispatchTouchEvent(ev);
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        if (editable.toString().contains("Submit")) {

            View rootview = newCommonlyEndActivity.this.getWindow().getDecorView();
            View aaa = rootview.findFocus();
            switch (aaa.toString()) {
                case "etLot":
                    etLot.setText(editable.toString().replace("Submit", ""));
                    etTrackOutNum.requestFocus();
                    break;
                case "etTrackOutNum":
                    etTrackOutNum.setText(editable.toString().replace("Submit", ""));
                    etProjectNum.requestFocus();
                    break;
                case "etProjectNum":
                    etProjectNum.setText(editable.toString().replace("Submit", ""));
                    etMaterielModel.requestFocus();
                    break;
            }
            Submit();
        }
    }

}